package server

import (
	"chitchat_http/model"
	"chitchat_http/util"
	"crypto/md5"
	"errors"
	"fmt"
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/sql_aid"
	"math/rand"
	"time"
)

// UserLogin 登录
func UserLogin(userId int64,RemoteAddr string) (map[string]interface{}, error) {

	list := make(map[string]interface{})
	list["user_id"] = userId
	//获取用户习惯
	userPropertySql, args := sql_aid.PgTable(model.TableByUserSign).Field("is_admin").Where("user_id = ?", userId).ToSql()
	userProperty, err := sql_aid.DataToMap(model.PgSql.Query(userPropertySql, args...))
	if err != nil || len(userProperty) == 0 {
		gogo_log.Error("server_UserLogin", "用户登录", err.Error())
		return nil, errors.New("用户不存在1")
	}
	list["property"] = userProperty[0]
	//生成token信息
	tokenToStringOne := fmt.Sprintf("%v", userId) + time.Now().Format("2006-05-04 15:02:01")
	tokenToMd5One := fmt.Sprintf("%x", md5.Sum([]byte(tokenToStringOne)))
	tokenToStringTwo := tokenToMd5One + time.Now().Format("2006-05-04 15:02:01")
	tokenToMd5Two := fmt.Sprintf("%x", md5.Sum([]byte(tokenToStringTwo)))
	token := fmt.Sprintf("%v-%v", userId, tokenToMd5Two)
	//
	tokenStruct := UserToken{ //token保存信息
		Token:   token,
		UserId:  userId,
		IsAdmin: int(userProperty[0]["is_admin"].(int64)),
	}
	if err := tokenStruct.TokenBySetToken(); err != nil {
		return nil, err
	}
	list["token"] = token

	//用户登录记录
	userUpdate := make(map[string]interface{})
	userUpdate["last_login_ip"] = RemoteAddr
	userUpdate["last_login_time"] = time.Now().Format(time.RFC3339)
	userSql,args := sql_aid.PgTable(model.TableByUserLogin).Where("user_id = ?",userId).UpdateByMap(userUpdate)
	_,err = model.PgSql.Exec(userSql,args...)
	if err != nil {
		gogo_log.Error("server_UserLogin", "user登录更改登录地址错误", err.Error())
		return nil ,errors.New("登录失败")
	}
	return list, nil
}

// UserRegisterByUsername 账号注册
func UserRegisterByUsername(username string, password string) (int64, error) {
	//检查账号是否存在
	set, args := sql_aid.PgTable(model.TableByUserLogin).Where("username = ?", username).ToSql()
	datas, err := sql_aid.DataToMap(model.PgSql.Query(set, args...))
	if err != nil || len(datas) != 0 {
		return 0, errors.New("账号已经存在")
	}
	//进行添加用户操作
	userReg := make(map[string]interface{})
	rand.Seed(time.Now().Unix())
	userReg["nick"] = fmt.Sprintf("%d", rand.Intn(100)) + fmt.Sprintf("%d", time.Now().Unix())
	tx, err := model.PgSql.Begin()
	defer tx.Rollback()
	userSql, args := sql_aid.PgTable(model.TableByUser).InsertByMap(userReg)
	var userId int64
	err = tx.QueryRow(userSql+" RETURNING id", args...).Scan(&userId)
	if err != nil {
		gogo_log.Error("server_UserRegisterByUsername", "user添加数据失败", err.Error())
		return 0, errors.New("添加用户失败")
	}
	userSignReg := make(map[string]interface{})
	userSignReg["user_id"] = userId
	userSignSql, args := sql_aid.PgTable(model.TableByUserSign).InsertByMap(userSignReg)
	_, err = tx.Exec(userSignSql, args...)
	if err != nil {
		gogo_log.Error("server_UserRegisterByUsername", "添加用户标识失败", err.Error())
		return 0, errors.New("添加用户标识失败")
	}
	userPropertyReg := make(map[string]interface{})
	userPropertyReg["user_id"] = userId
	userPropertySql, args := sql_aid.PgTable(model.TableByUserProperty).InsertByMap(userPropertyReg)
	_, err = tx.Exec(userPropertySql, args...)
	if err != nil {
		gogo_log.Error("server_UserRegisterByUsername", "添加用户钱包失败", err.Error())
		return 0, errors.New("添加用户钱包失败")
	}
	userLoginReg := make(map[string]interface{})
	userLoginReg["user_id"] = userId
	userLoginReg["username"] = username
	//userLoginReg["mobile"] = ""
	userLoginReg["password"] = string(util.Hash(password))
	//userLoginReg["e_mail"] = ""
	//userLoginReg["wx_open_id"] = ""
	//userLoginReg["wx_union_id"] = ""
	userLoginReg["time_c"] = time.Now().Format(time.RFC3339)
	userLoginReg["is_login"] = model.UserLoginByIsLoginNormal
	userLoginSql, args := sql_aid.PgTable(model.TableByUserLogin).InsertByMap(userLoginReg)
	_, err = tx.Exec(userLoginSql, args...)
	if err != nil {
		gogo_log.Error("server_UserRegisterByUsername", "登录信息添加失败", err.Error())
		return 0, errors.New("登录信息添加失败")
	}
	tx.Commit()
	return userId, nil
}

// UserByChangePassword 修改密码
func UserByChangePassword(userId int64, password string) error {
	update := make(map[string]interface{})
	update["password"] = string(util.Hash(password))
	updateSql, rage := sql_aid.PgTable(model.TableByUserLogin).Where("user_id = ?", userId).UpdateByMap(update)
	_, err := model.PgSql.Exec(updateSql, rage...)
	if err != nil {
		gogo_log.Error("server_UserByChangePassword", "登录信息添加失败", err.Error())
		return errors.New("更改失败")
	}
	return nil
}

// UserByList 用户列表
func UserByList(input map[string]string) []map[string]interface{} {
	if input["orderBy"] == "" { //默认排序
		input["orderBy"] = "id desc"
	}
	//排序
	goodsSql, arge := sql_aid.PgTable(model.TableByUser).Field("id", "username", "mobile", "nick", "avatar", "last_login_ip", "last_login_time", "time_c").WhereRaw(func(query *sql_aid.PgQuery, i ...interface{}) {
		if i[0].(map[string]string)["nick"] != "" { //用户昵称
			query.Where("nick like ?", "%"+i[0].(map[string]string)["nick"]+"%")
		}
		if i[0].(map[string]string)["username"] != "" { //登录账号
			query.Where("username like %?%", i[0].(map[string]string)["username"])
		}
		if i[0].(map[string]string)["mobile"] != "" { //手机号
			query.Where("mobile like %?%", i[0].(map[string]string)["mobile"])
		}
		//if i[0].(map[string]string)["status"] != "" { //状态:1=正常,2=禁用
		//	query.Where("status = ?", i[0].(map[string]string)["status"])
		//}
	}, input).OrderBy(input["orderBy"]).PageSize(input["page"], input["page_size"]).ToSql()
	goodsData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSql, arge...))
	if err != nil {
		gogo_log.Error("server_UserByList", "用户列表", err.Error())
		return []map[string]interface{}{}
	}
	return goodsData
}
